package suanfa;

import org.junit.Test;

public class CharToIn
{
    public int myAtoi(String str) {
        char[] chars = str.toCharArray();
        String last="";
        int j = chars.length;
        if (j == 0)
        {
            return 0;
        }
        int m =1;
        for (int i = 0; i < j; i++)
        {

            if (chars[i] == ' ')
            {
                last = str.substring(i + 1, j);
                if (i != 0)
                {
                    m = i+1;
                }

            }
            else if (chars[i] == '-'||chars[i]=='+')
            {
                if (i + 1 == j)
                {
                    break;
                }
                //非整数判断
                if (chars[i + 1] < 48 || chars[i + 1] > 57)
                {
                    last = "0";
                    break;
                }
                //如果是整数的话，那么截取负号和整数
                last = str.substring(i, j);
            }
            else
            {
                //非整数判断
                if (chars[i] >= 48 && chars[i] <= 57)
                {
                    last = str.substring(m-1,i+1).replace(" ","");
                    if (i + 1 == j)
                    {
                        break;
                    }
                    if (chars[i + 1] < 48 || chars[i + 1] > 57)
                    {
                        break;
                    }
                }

                if (i + 1 == j)
                {
                    break;
                }
                if (chars[i + 1] < 48 || chars[i + 1] > 57)
                {
                    last = "0";
                    break;
                }
                if (chars[i] < 48 || chars[i] > 57)
                {
                    last = "0";
                    break;
                }

            }
        }

        try
        {
            Double.valueOf(last);
        }
        catch (NumberFormatException e)
        {
            return 0;
        }
        if (Double.valueOf(last) < Integer.MIN_VALUE)
        {
            return Integer.MIN_VALUE;
        }
        if (Double.valueOf(last) > Integer.MAX_VALUE)
        {
            return Integer.MAX_VALUE;
        }

        return Integer.valueOf(last);
    }

    @Test
    public void test()
    {

        int i = myAtoi("20000000000000000000");
        System.out.println(i);
    }
}
